package com.styles.codingstyle.config;

import com.styles.codingstyle.Handle.CustomAccessDeniedHandler;
import com.styles.codingstyle.Security.service.UserServiceForSecurityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Package com.styles.codingstyle.config
 * @Description: Security相关配置
 * @Author 陈建
 * @Create: 2018-06-07 09:07
 * @Version 1.0
 * @Update: message
 */
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceForSecurityImpl userServiceForSecurity;

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    /**
     * @Description: 基础拦截配置
     * @Param: [http]
     * @Return: void
     * @Author: 陈建
     * @date: 2018/6/7 9:37
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/fonts/**").permitAll()  // 允许访问资源
                .antMatchers("/", "/index/**").permitAll() //允许访问这三个路由
                .antMatchers("/admin/**").hasAnyRole("ADMIN")   // 满足该条件下的路由需要ROLE_ADMIN的角色
                .antMatchers("/user/**").hasAnyRole("USER")     // 满足该条件下的路由需要ROLE_USER的角色
                .antMatchers("/dba/**").hasAnyRole("DBA")     // 满足该条件下的路由需要ROLE_DBA的角色
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll().defaultSuccessUrl("/index")
                .and()
                .logout().permitAll();
        //.and()
        //.csrf().disable()
        // .exceptionHandling().accessDeniedHandler(customAccessDeniedHandler);   //自定义异常处理

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userServiceForSecurity).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
